import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/address/MyAddress.dart';
import 'package:panda/base/Constant.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/address_entity.dart';
import 'package:panda/entity/coupon.dart';
import 'package:panda/event/order_refresh.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/BlankToolBarTool.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';

class BuyGoodsPage extends StatefulWidget {
  String goods_name = "";
  String goods_id = "";
  String goods_img = "";
  String price = "";
  String skuJson = "";
  String skuInfo = "";
  String goods_num;
  String type = "0";
  String old = "0";
  String id = "0";
  String is_vip = "0";
  BuyGoodsPage(
      {Key key,
      @required this.goods_id,
      @required this.goods_name,
      @required this.old,
      @required this.goods_img,
      this.is_vip,
      @required this.price,
      @required this.skuJson,
      @required this.goods_num,
      this.type,
      this.id,
      @required this.skuInfo})
      : super(key: key);

  _BuyGoodsPageState createState() => _BuyGoodsPageState();
}

class _BuyGoodsPageState extends State<BuyGoodsPage>
    with WidgetsBindingObserver {
  var selectAddress = "";
  var selectId = "";
  var selectNameAndPhone = "";
  String token = "", phone = "";
  BlankToolBarModel barModel = BlankToolBarModel();
  String yunfei = "0.00";
  Map userMap = null;
  int num_buy = 1, selectCoupon = -2;

  String remark = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    barModel.outSideCallback = focusNodeChange;
    num_buy = int.parse(widget.goods_num);
    getString(TOKEN).then((value) {
      token = value;
      loadList();
      getCouponsList();
    });
    phone = APPLIC.userInfoMap["user_msg"]['phone'];
  }

  void focusNodeChange() {
    setState(() {});
  }

  @override
  void dispose() {
    barModel.removeFocusListeners();

    super.dispose();
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = "1";
    map['per'] = "1000";
    map['sign_type'] = SignType.GET_USER_ADDRESS;
    Response<String> response =
        await HttpUtil().post(Api.USER_ADDRESSLIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    AddressListEntity homeListEntity = new AddressListEntity.fromJson(userMap);
    if (mounted) {
      for (int i = 0; i < homeListEntity.data.datas.length; i++) {
        if (homeListEntity.data.datas[i].is_default == "Y") {
          selectAddress = homeListEntity.data.datas[i].province +
              homeListEntity.data.datas[i].city +
              homeListEntity.data.datas[i].county +
              homeListEntity.data.datas[i].detail_address;
          selectId = homeListEntity.data.datas[i].id;
          selectNameAndPhone = homeListEntity.data.datas[i].consignee +
              "  " +
              homeListEntity.data.datas[i].contact_number;
          break;
        }
      }
      if (selectId != "") getYunFei();
      setState(() {});
    }
  }

  getYunFei() async {
    Map map = new Map();
    map['token'] = token;
    List<Map> goodsList = new List();
    for (int i = 0; i < 1; i++) {
      Map map1 = new Map();
      map1['"goods_id"'] = widget.goods_id;
      map1['"num"'] = widget.goods_num;
      goodsList.add(map1);
    }
    map['goodslist'] = goodsList.toString();
    map['address_id'] = selectId;
    print(map);
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/Order/getPostage",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      print(response);
      yunfei = userMap['postage'].toString();
      setState(() {});
    }
  }

  List<UserCouponListDataData> dataList = new List();

  getCouponsList() async {
    Map map = new Map();
    map['token'] = token;
    // map['sign_type'] = "dmshop.UserCouponsRecord.getList";
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/UserCouponsRecord/getList",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    UserCouponListEntity homeListEntity =
        new UserCouponListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      dataList.addAll(homeListEntity.data.datas);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return Container(
        child: new Scaffold(
      appBar: AppBar(
        title: Text('提交订单', style: TextStyle(fontSize: 18, color: black)),
        backgroundColor: white,
        brightness: Brightness.light,
        iconTheme: IconThemeData(color: black_99),
        elevation: 1.0,
      ),
      resizeToAvoidBottomInset: false,
      body: BlankToolBarTool.blankToolBarWidget(context,
          model: barModel,
          body: Column(
            children: <Widget>[
              Expanded(
                  child: SingleChildScrollView(
                child: new Container(
                  color: white,
                  height: MediaQuery.of(context).size.height,
                  child: new Column(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.all(15),
                        child: new Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Image.asset('images/icon_order_location.png'),
                            Expanded(
                              child: GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context)
                                      .push<AddressListDataData>(
                                          MaterialPageRoute(builder: (context) {
                                    return MyAddressPage(
                                      type: 1,
                                    );
                                  })).then((AddressListDataData data) {
                                    print(data);
                                    if (data != null)
                                      setState(() {
                                        selectAddress = data.province +
                                            data.city +
                                            data.county +
                                            data.detail_address;
                                        selectId = data.id;
                                        selectNameAndPhone = data.consignee +
                                            "  " +
                                            data.contact_number;
                                        getYunFei();
                                      });
                                  });
                                },
                                child: selectAddress == ""
                                    ? Padding(
                                        padding:
                                            EdgeInsets.fromLTRB(10, 0, 10, 0),
                                        child: Text('请选择收货地址',
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                color: Colors.black45)))
                                    : Padding(
                                        padding:
                                            EdgeInsets.fromLTRB(10, 0, 10, 0),
                                        child: new Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          mainAxisAlignment:
                                              MainAxisAlignment.center,
                                          children: <Widget>[
                                            Text(selectAddress,
                                                style: TextStyle(
                                                    color: black,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(
                                                            NORMAL_FONT_SIZE),
                                                    fontWeight:
                                                        FontWeight.w500)),
                                            Padding(
                                              padding: EdgeInsets.fromLTRB(
                                                  0, 8, 0, 0),
                                              child: Text(selectNameAndPhone,
                                                  style: TextStyle(
                                                    color: black_99,
                                                    fontSize: ScreenUtil
                                                            .getInstance()
                                                        .setSp(SMALL_FONT_SIZE),
                                                  )),
                                            )
                                          ],
                                        ),
                                      ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                Navigator.of(context).push<AddressListDataData>(
                                    MaterialPageRoute(builder: (context) {
                                  return MyAddressPage(
                                    type: 1,
                                  );
                                })).then((AddressListDataData data) {
                                  if (data == null) {
                                    return;
                                  }
                                  setState(() {
                                    selectAddress = data.province +
                                        data.city +
                                        data.county +
                                        data.detail_address;
                                    selectId = data.id;
                                    selectNameAndPhone = data.consignee +
                                        "  " +
                                        data.contact_number;
                                  });
                                  getYunFei();
                                });
                              },
                              child: Container(
                                color: white,
                                child: Icon(Icons.arrow_forward_ios),
                              ),
                            )
                          ],
                        ),
                      ),
                      Container(
                        height: 10,
                        color: divideColor,
                        margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
                      ),
                      Container(
                        padding: EdgeInsets.all(15),
                        child: new Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            widget.goods_img == ""
                                ? Image.asset(
                                    'images/app_icon.png',
                                    width: ScreenUtil.getInstance()
                                        .setHeight(DP_120),
                                    height: ScreenUtil.getInstance()
                                        .setHeight(DP_120),
                                    fit: BoxFit.fill,
                                  )
                                : CachedNetworkImage(
                                    imageUrl: widget.goods_img.contains("http")
                                        ? widget.goods_img
                                        : Api.ImgBaseUrl + widget.goods_img,
                                    width: ScreenUtil.getInstance()
                                        .setHeight(DP_120),
                                    height: ScreenUtil.getInstance()
                                        .setHeight(DP_120),
                                    fit: BoxFit.fill,
                                  ),
                            Expanded(
                              flex: 1,
                              child: Container(
                                padding: EdgeInsets.fromLTRB(10, 0, 5, 5),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      widget.goods_name,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE),
                                          color: black,
                                          fontWeight: FontWeight.w500),
                                    ),
                                    Padding(
                                      padding: EdgeInsets.fromLTRB(0, 5, 5, 0),
                                      child: Text(
                                        widget.skuInfo,
                                        style: TextStyle(
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(MINI_FONT_SIZE),
                                            color: black_99),
                                      ),
                                    ),
                                    Container(
                                      height: 5,
                                    ),
                                    Text(
                                      '¥' + widget.old,
                                      style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(30),
                                          color: black),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.fromLTRB(0, 0, 10, 10),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text('',
                                  style: TextStyle(color: black, fontSize: 14)),
                            ),
                            Text('共',
                                style: TextStyle(
                                    color: black_99,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE + 2))),
                            Text(num_buy.toString(),
                                style: TextStyle(
                                    color: Colors.red,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE + 2))),
                            Text('件商品，合计:',
                                style: TextStyle(
                                    color: black_99,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(SMALL_FONT_SIZE + 2))),
                            Text(
                              formatNum(
                                  (double.parse(widget.old) * num_buy), 2),
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                  color: black),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Text('订单备注',
                                style: TextStyle(
                                    color: black,
                                    fontSize: ScreenUtil.getInstance()
                                        .setSp(NORMAL_FONT_SIZE))),
                            Container(height: 5),
                            Container(
                                padding: EdgeInsets.all(5),
                                decoration: BoxDecoration(
                                    color: f0Color,
                                    borderRadius: BorderRadius.circular(5)),
                                child: new TextField(
                                  onChanged: (value) {
                                    remark = value;
                                  },
                                  keyboardType: TextInputType.text,
                                  maxLines: 2,
                                  keyboardAppearance: Brightness.light,
                                  cursorColor: mainColor,
                                  // controller: userController,
                                  style: TextStyle(
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE)),
                                  decoration: new InputDecoration(
                                      hintText: "订单备注不要超过50个字哦",
                                      border: InputBorder.none,
                                      hintStyle: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(NORMAL_FONT_SIZE))),
                                ))
                          ],
                        ),
                      ),

                      Container(height: 5),
                      Container(
                        height: 10,
                        color: divideColor,
                        margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
                      ),
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 8, 10, 0),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text('商品总价',
                                  style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE))),
                            ),
                            Text(
                              MONEY +
                                  formatNum(
                                      (double.parse(widget.old) * num_buy), 2),
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(30),
                                  color: black),
                            ),
                          ],
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 8, 10, 0),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text('运费',
                                  style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE))),
                            ),
                            Text(
                              '$yunfei',
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(30),
                                  color: black_99),
                            ),
                          ],
                        ),
                      ),
                      // Container(
                      //   height: 10,
                      //   color: divideColor,
                      //   margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
                      // ),
                      
                      Padding(
                        padding: EdgeInsets.fromLTRB(10, 3, 10, 10),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text('立省',
                                  style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE))),
                            ),
                            Text(
                              MONEY +
                                  formatNum(
                                      (double.parse(widget.old) * num_buy -
                                          double.parse(widget.price) * num_buy),
                                      2),
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(30),
                                  color: Colors.red),
                            ),
                          ],
                        ),
                      ),
                     
                      dataList.length == 0
                  ?  Padding(
                        padding: EdgeInsets.fromLTRB(10, 3, 10, 13),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text('优惠券',
                                  style: TextStyle(color: black, fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE))),
                            ),
                            Text(
                              "无可用优惠",
                              style: TextStyle(
                                  fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                                  color: Colors.black87),
                            ),
                          ],
                        ),
                      )
                  : Container(
                      padding: EdgeInsets.fromLTRB(10, 3, 10, 13),
                      color: white,
                      child: new GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          showCoupons(context);
                        },
                        child: new Row(
                          children: <Widget>[
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.fromLTRB(0, 0, 15, 0),
                                child: Text("优惠券",
                                    style: TextStyle(
                                      color: black,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                    )),
                              ),
                            ),
                            Text(
                                selectCoupon == -1
                                    ? '暂不使用券':selectCoupon == -2
                                    ? '选择优惠券'
                                    : MONEY+dataList[selectCoupon].money,
                                style: TextStyle(
                                  color: black_99,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE),
                                )),
                            Container(width: 10),
                            Icon(Icons.arrow_forward_ios,
                                size: 15, color: Colors.black54)
                          ],
                        ),
                      ),
                    ),
                     Container(
                        color: divideColor,
                        height: 10,
                      ),
                    ],
                  ),
                ),
              )),
              
              Padding(
                padding: EdgeInsets.fromLTRB(20, 20, 20, 40),
                child: Row(
                  children: <Widget>[
                    Text(
                      "应付",
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance().setSp(26),
                          color: black),
                    ),
                    Expanded(
                      flex: 1,
                      child: Text(
                       dataList.length==0||selectCoupon==-1||selectCoupon==-2? MONEY +
                            formatNum(
                                (double.parse(widget.price) * num_buy +
                                    double.parse(yunfei)),
                                2):MONEY +
                            formatNum(
                                (double.parse(widget.price) * num_buy- double.parse(dataList[selectCoupon].money)+
                                    double.parse(yunfei)),
                                2),
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(40),
                            color: Colors.red),
                      ),
                    ),
                    new Container(
                      height: 35,
                      decoration: new BoxDecoration(
                          color: mainColor,
                          borderRadius: BorderRadius.circular(10.0)),
                      child: new FlatButton(
                        child: new Padding(
                          padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                          child: new Text(
                            "确定下单",
                            style: new TextStyle(
                                color: Colors.white,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE)),
                          ),
                        ),
                        onPressed: () {
                          if (selectId == "") {
                            Fluttertoast.showToast(msg: "请选择收货地址");
                            return;
                          }
                          showDialog(
                              context: context,
                              barrierDismissible: false,
                              builder: (_) {
                                return new NetLoadingDialog(
                                  loadingText: "下单中...",
                                  bgColor: Color.fromARGB(255, 0, 0, 0),
                                  requestCallBack: null,
                                  outsideDismiss: false,
                                );
                              });
                          buy();
                        },
                      ),
                    )
                  ],
                ),
              )
            ],
          )),
    ));
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      return num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    } else {
      return num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString();
    }
  }

  showCoupons(BuildContext context) {
    showModalBottomSheet(
        isScrollControlled: true,
        context: context,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return StatefulBuilder(
            builder: (BuildContext context, setState) {
              return new Container(
                height: MediaQuery.of(context).size.height * 2 / 3,
                padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(15),
                      topRight: Radius.circular(15),
                    ),
                    color: white),
                child: new Column(
                  children: <Widget>[
                    new Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: <Widget>[
                        GestureDetector(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          behavior: HitTestBehavior.opaque,
                          child: Container(
                            margin:
                                EdgeInsets.only(top: 10, right: 10, bottom: 10),
                            width: 25,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(25),
                                color: Colors.black),
                            height: 25,
                            child: Icon(
                              Icons.close,
                              color: white,
                            ),
                          ),
                        )
                      ],
                    ),
                    Container(
                      height: MediaQuery.of(context).size.height * 2 / 3 - 45,
                      child: SingleChildScrollView(
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: [
                                Expanded(child: Center()),
                                Text('选择优惠券',
                                    style: TextStyle(
                                        color: black,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(35))),
                                Expanded(
                                    child: Center(
                                        child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    selectCoupon = -1;
                                    Navigator.of(context).pop();
                                    updatae();
                                  },
                                  child: Text('暂不使用',
                                      style: TextStyle(
                                          color: mainColor,
                                          fontSize: ScreenUtil.getInstance()
                                              .setSp(30))),
                                ))),
                              ],
                            ),
                            ListView.builder(
                              physics: NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) {
                                return Container(
                                  margin: EdgeInsets.only(top: 10),
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                          color:  mainColor,
                                          width: 1),
                                      borderRadius: BorderRadius.circular(10)),
                                  padding: EdgeInsets.all(
                                      ScreenUtil.getInstance()
                                          .setHeight(DP_20)),
                                  child: Row(
                                    children: <Widget>[
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(MONEY + dataList[index].money,
                                                style: TextStyle(
                                                    fontSize:
                                                        ScreenUtil.getInstance()
                                                            .setSp(
                                                                BIG_FONT_SIZE +
                                                                    10),
                                                    fontWeight: FontWeight.bold,
                                                    color: (double.parse(widget
                                                                    .price) *
                                                                num_buy) <
                                                            double.parse(dataList[
                                                                    index]
                                                                .condition_money)
                                                        ? Colors.grey
                                                        : mainColor)),
                                            Container(
                                              height: ScreenUtil.getInstance()
                                                  .setWidth(DP_8),
                                            ),
                                            Text(
                                               dataList[index].name,
                                                style: TextStyle(
                                                    fontSize:
                                                        ScreenUtil.getInstance()
                                                            .setSp(
                                                                MINI_FONT_SIZE+3),
                                                    color: black_99)),
                                          ],
                                        ),
                                        flex: 1,
                                      ),
                                      Expanded(
                                          child: Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: <Widget>[
                                              Text("有效日期",
                                                  style: TextStyle(
                                                      fontSize: ScreenUtil
                                                              .getInstance()
                                                          .setSp(
                                                              NORMAL_FONT_SIZE),
                                                      color: black)),
                                              Container(
                                                height: ScreenUtil.getInstance()
                                                    .setWidth(DP_15),
                                              ),
                                              Text(
                                                  dataList[index]
                                                          .use_start_time
                                                          .split(' ')[0] +
                                                      '至' +
                                                      dataList[index]
                                                          .use_end_time
                                                          .split(' ')[0],
                                                  style: TextStyle(
                                                      fontSize: ScreenUtil
                                                              .getInstance()
                                                          .setSp(
                                                              MINI_FONT_SIZE),
                                                      color: Colors.black45)),
                                            ],
                                          ),
                                          flex: 2),
                                      GestureDetector(
                                        child: Container(
                                            child: Text(
                                                (double.parse(widget.price) * num_buy) <
                                                        double.parse(
                                                            dataList[index]
                                                                .condition_money)
                                                    ? '不可使用'
                                                    : '立即使用',
                                                style: TextStyle(
                                                    fontSize:
                                                        ScreenUtil.getInstance()
                                                            .setSp(30),
                                                    color: (double.parse(widget.price) *
                                                                num_buy) <
                                                            double.parse(
                                                                dataList[index].condition_money)
                                                        ? Colors.grey
                                                        : mainColor))),
                                        onTap: () {
                                          if ((double.parse(widget.price) *
                                                  num_buy) <
                                              double.parse(dataList[index]
                                                  .condition_money)) {
                                            return;
                                          }
                                          selectCoupon = index;
                                          Navigator.of(context).pop(1);
                                          updatae();
                                        },
                                        behavior: HitTestBehavior.opaque,
                                      )
                                    ],
                                  ),
                                );
                              },
                              itemCount: dataList.length,
                              padding: EdgeInsets.all(0),
                              shrinkWrap: true,
                            ),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              );
            },
          );
        });
  }

  updatae() {
    setState(() {});
  }

  buy() async {
    if (widget.type == "1") {
      Map map = new Map();
      map['token'] = token;
      map['id'] = widget.id;
      map['goods_sku'] = widget.skuJson;
      map['num'] = num_buy;
      map['remark'] = ""; //remark
      map['address_id'] = selectId;
      map['sign_type'] = SignType.QIANGGOU_ORDER;
      Response<String> response =
          await HttpUtil().post(Api.QIANGGOU_ORDER, data: getSign(map));
      userMap = json.decode(response.data);
      int code = userMap['code'];
      Navigator.of(context).pop(1);
      if (code == 1) {
        Fluttertoast.showToast(msg: '下单成功');
        APPLIC.eventBus.fire(OrderRefreshEvent("1"));
        Navigator.of(context).pop("1");
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderPayPage(
        //       orderId: userMap['data']['order_id'],
        //       title: userMap['data']['title'],
        //       orderNum: userMap['data']['order_num'],
        //       totalMoney: userMap['data']['allprice'].toString());
        // }));
      } else {
        Fluttertoast.showToast(msg: userMap['msg']);
        userMap = null;
      }
      return;
    }
    Map map = new Map();
    map['token'] = token;
    map['goods_id'] = widget.goods_id;
    map['goods_sku'] = widget.skuJson;
    map['num'] = num_buy;
    if(selectCoupon!=-2&&selectCoupon!=-1&&dataList.length!=0){
        map['coupons_id'] = dataList[selectCoupon].id;
    }
    map['remark'] = remark;
    map['address_id'] = selectId;
    map['sign_type'] = SignType.BUY_GOODS;
    print(map);
    Response<String> response = await HttpUtil().post(
        widget.is_vip == "1"
            ? Api.BaseUrl + "/index.php/wap/UserOrder/order"
            : Api.BUY_GOODS,
        data: getSign(map));
    userMap = json.decode(response.data);
    int code = userMap['code'];
    Navigator.of(context).pop(1);
    if (code == 1) {
      APPLIC.eventBus.fire(OrderRefreshEvent("1"));
      Fluttertoast.showToast(msg: '下单成功');
      Navigator.of(context).pop(userMap);
    } else {
      Fluttertoast.showToast(msg: userMap['msg']);
      userMap = null;
    }
  }
}
